package modelo;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import com.thoughtworks.xstream.XStream;
import static modelo.SetUps.N_ARCH_NIVEL;
import static modelo.SetUps.N_ARCH_JUGADOR;

public class PersistenciaNivel {

	private Nivel nivel;
	
	public PersistenciaNivel() {
	}

	public PersistenciaNivel(Nivel nivel) {
		this.nivel = nivel;
	}

	public void persistir (String path) throws IOException{
		//jugador
		Jugador jugador = nivel.getJugador();
		XStream xstream = new XStream();
		xstream.alias("Jugador", jugador.getClass());
		FileWriter xmlFile = new FileWriter(getPathJugador (path));
		xstream.toXML(jugador,xmlFile);
		
		//cambio nivel
		CambioNivel cambioNivel = nivel.getCambioNivel();
		XStream xstreamNivel = new XStream();
		xstreamNivel.alias("CambioNivel", cambioNivel.getClass());
		FileWriter xmlFileNivel = new FileWriter(getPathNivel (path));
		xstreamNivel.toXML(cambioNivel,xmlFileNivel);
		
		xmlFile.close();
		xmlFileNivel.close();
		
	}

	public void cargar(String path) throws IOException{
			XStream xstreamNivel = new XStream();
			CambioNivel cambioNivel;
			xstreamNivel.alias("CambioNivel", CambioNivel.class);
			FileReader file = new FileReader(getPathNivel(path));
			cambioNivel = (CambioNivel)xstreamNivel.fromXML(file);
			file.close();
			XStream xstreamJugador = new XStream();
			Jugador jugador;
			xstreamJugador.alias("Jugador",Jugador.class);
			file = new FileReader(getPathJugador (path));
			jugador = (Jugador) xstreamJugador.fromXML(file);
			file.close();			
			this.nivel = new Nivel (jugador, cambioNivel);
	}

	public Escenario getEscenario() {
		return nivel.getEscenario();
	}
	
	public Nivel getNivel (){
		return nivel;
	}
	
	private String getPathJugador (String path){
		return new File (path,N_ARCH_JUGADOR).toString();
	}

	private String getPathNivel (String path){
		return new File (path,N_ARCH_NIVEL).toString();
	}
}
